import JSZip from 'jszip'
import { saveAs } from 'file-saver'

type TimeType = Date | string | number | null
export interface IZipItem {
  name: string
  file: Blob
}

/**
 * @description 获取当前时间对应的提示语
 * @returns {String}
 */
export const getTimeState = () => {
  const timeNow = new Date()
  const hours = timeNow.getHours()
  if (hours >= 6 && hours <= 10) return `早上好 ⛅`
  if (hours >= 10 && hours <= 14) return `中午好 🌞`
  if (hours >= 14 && hours <= 18) return `下午好 🌞`
  if (hours >= 18 && hours <= 24) return `晚上好 🌛`
  if (hours >= 0 && hours <= 6) return `凌晨好 🌛`
}

/**
 * 将时间解析为字符串
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export const parseTime = (time?: TimeType, cFormat?: string): string => {
  let inputTime = time
  if (inputTime === undefined || !inputTime) {
    return ''
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date: Date
  if (typeof inputTime === 'object') {
    date = inputTime as Date
  } else {
    if (typeof inputTime === 'string') {
      if (/^[0-9]+$/.test(inputTime)) {
        inputTime = parseInt(inputTime)
      } else {
        // ios 日期格式兼容 safari
        inputTime = inputTime.replace(/-/gm, '/')
      }
    }
    if (typeof inputTime === 'number' && inputTime.toString().length === 10) {
      inputTime = inputTime * 1000
    }
    date = new Date(inputTime)
  }
  const formatObj: { [key: string]: number } = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  return format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // 请注意: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
}

/**
 * 获取assets静态资源
 * @param url 文件路径
 */
export const getAssetsFile = (url: string) => {
  return new URL(`../assets/images/${url}`, import.meta.url)
}

/**
 * 解析性别
 * @param {number} num
 * @returns {string}
 */
export function gender(num: string | number): string | number {
  switch (num) {
    case 0:
    case '0':
    case '女':
      return '女'
    case 1:
    case '1':
    case '男':
      return '男'
    case '-':
      return '--'
    default:
      return '--'
  }
}

/**
 * 数字转字母
 * @param number
 */
export function numberToLetter(number: number) {
  if (number < 1 || number > 26) {
    throw new Error('数字必须在1到26之间')
  }
  return String.fromCharCode(64 + number)
}

/**
 * 数字转中文,例：数字1 转为 中文一
 * @param {number} num
 * @returns {string}
 */
export function numToChineseNum(num: number) {
  const arr1 = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const arr2 = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿'] // 可继续追加更高位转换值
  if (!num || isNaN(num)) {
    return '零'
  }
  const english = num.toString().split('')
  let result = ''
  for (let i = 0; i < english.length; i++) {
    const des_i = english.length - 1 - i // 倒序排列设值
    result = arr2[i] + result
    const arr1_index = Number(english[des_i])
    result = arr1[arr1_index] + result
  }
  // 将【零千、零百】换成【零】 【十零】换成【十】
  result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十')
  // 合并中间多个零为一个零
  result = result.replace(/零+/g, '零')
  // 将【零亿】换成【亿】【零万】换成【万】
  result = result.replace(/零亿/g, '亿').replace(/零万/g, '万')
  // 将【亿万】换成【亿】
  result = result.replace(/亿万/g, '亿')
  // 移除末尾的零
  result = result.replace(/零+$/, '')
  // 将【零一十】换成【零十】
  // result = result.replace(/零一十/g, '零十');//貌似正规读法是零一十
  // 将【一十】换成【十】
  result = result.replace(/^一十/g, '十')
  return result
}

/* 数字转百分比
 * @param num 值
 * @param decimals 小数位数 默认1
 * @returns number
 */
export const numberToPercent = (num: number, decimals = 1) => {
  if (typeof num !== 'number' || isNaN(num)) {
    return 0
  }
  if (num === 0) {
    return 0
  }
  return decimals === 0 ? Math.round(num * 100) : Number((num * 100).toFixed(decimals))
}

/**
 * 下载文件
 * @param url 文件地址
 */
export function downloadFile(url: string) {
  const arr = url.split('/')
  const index = arr.length - 1
  const name = arr[index]
  const link = document.createElement('a')
  fetch(url)
    .then(res => res.blob())
    .then(blob => {
      // 将链接地址字符内容转变成blob地址
      link.href = URL.createObjectURL(blob)
      link.download = name || ''
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
}

/**
 * enum 转为数组(注意，此函数只能用于数字枚举)
 * @param enumObj
 * @returns
 */
export const enumToArray = <T>(enumObj: any): { label: string; value: T }[] => {
  return Object.keys(enumObj)
    .filter(key => isNaN(Number(key)))
    .map(key => {
      return {
        label: key,
        value: enumObj[key]
      }
    })
}

/**
 * 打包成压缩文件
 * @param list pdf文件列表
 * @param zipName 导出的包名
 */
export const handleZipFile = async (list: IZipItem[], zipName: string) => {
  const zip = new JSZip()
  for await (const item of list) {
    zip.file(`${item.name}.pdf`, item.file)
  }
  const content = await zip.generateAsync({
    type: 'blob',
    compression: 'DEFLATE',
    compressionOptions: {
      level: 9
    }
  })
  saveAs(content, zipName)
}
